package com.example.microinvestweb.controller.ai;

import com.example.microinvestcommon.ai.AiMemory;
import com.example.microinvestcommon.util.ThreadLocalUtil;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.Map;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@RestController
@RequestMapping("/ai")
public class ChatController {

    private final ChatClient chatclient;

    private final AiMemory chatMemory;

    @Autowired(required = false)
    public ChatController(ChatClient chatClient, AiMemory ChatMemory) {
        this.chatclient = chatClient;
        this.chatMemory=ChatMemory;
    }

    @RequestMapping(value = "/chatStream", produces = "text/html;charset=UTF-8")
    private ResponseEntity<Flux<String>> chatStream(String message) {

        Map<String,Long> map = ThreadLocalUtil.get();
        System.out.println(map);
        Long userId=map.get("userId");

        try {
            Flux<String> response = chatclient.prompt()
                    .user(message)
                    .advisors(advisorSpec -> advisorSpec
                            .param(CHAT_MEMORY_CONVERSATION_ID_KEY,userId)
                            .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY,Integer.MAX_VALUE))
                    .stream().content();
            return ResponseEntity.ok()
                    // 设置内容类型为文本事件流
                    .contentType(MediaType.parseMediaType("text/html;charset=UTF-8"))
                    .body(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().build();
        }
    }


}
